package com.ruoyi.stock.listener;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import com.ruoyi.api.event.EventListener;
import com.ruoyi.api.event.EventType;
import com.ruoyi.api.event.OrderExecutionEvent;
import com.ruoyi.stock.domain.StockInventory;
import com.ruoyi.stock.service.IStockInventoryService;
import com.ruoyi.basedata.domain.BaseProduct;
import com.ruoyi.basedata.service.IBaseProductService;

import javax.annotation.PostConstruct;

/**
 * 采购订单执行事件监听器 - 用于更新库存数量
 */
@Component(value = "stockPurchaseOrderListener")
public class PurchaseOrderExecutionListener implements EventListener<OrderExecutionEvent> {

    private static final Logger logger = LoggerFactory.getLogger(PurchaseOrderExecutionListener.class);

    @Autowired
    private IStockInventoryService stockInventoryService;
    
    @Autowired
    private IBaseProductService baseProductService;
    
    @Autowired
    private com.ruoyi.api.event.EventCenter eventCenter;
    
    @PostConstruct
    public void init() {
        // 注册监听器
        eventCenter.registerListener(this);
        logger.info("Registered Stock PurchaseOrderExecutionListener");
    }

    @Override
    public void onEvent(OrderExecutionEvent event) {
        if (event.getEventType() != EventType.PURCHASE_ORDER_EXECUTED) {
            return;
        }
        
        logger.info("Processing purchase order execution event for stock update, order ID: {}", event.getOrderId());
        
        try {
            // 获取商品ID
            Long productId = null;
            if (event.getData("productId") != null) {
                productId = Long.valueOf(event.getData("productId").toString());
            } else {
                logger.error("Product ID not found in event data, cannot update inventory");
                return;
            }
            
            // 获取商品名称
            String productName = null;
            if (event.getData("productName") != null) {
                productName = event.getData("productName").toString();
            } else {
                logger.warn("Product name not found in event data, trying to fetch from base data");
                try {
                    // 尝试从基础数据模块获取商品名称
                    BaseProduct baseProduct = baseProductService.selectBaseProductByProductId(productId);
                    if (baseProduct != null && baseProduct.getProductName() != null) {
                        productName = baseProduct.getProductName();
                        logger.info("Found product name from base data: {}", productName);
                    } else {
                        logger.warn("Product not found in base data, using default name");
                        productName = "商品" + productId; // 默认名称
                    }
                } catch (Exception e) {
                    logger.error("Error getting product name from base data", e);
                    productName = "商品" + productId; // 默认名称
                }
            }
            
            // 获取采购数量
            Integer quantity = null;
            if (event.getData("quantity") != null) {
                quantity = Integer.valueOf(event.getData("quantity").toString());
            } else {
                logger.error("Quantity not found in event data, cannot update inventory");
                return;
            }
            
            // 查询该商品的库存记录
            StockInventory inventory = new StockInventory();
            inventory.setProductId(productId);
            inventory = stockInventoryService.selectStockInventoryList(inventory).stream()
                    .findFirst().orElse(null);
            
            if (inventory == null) {
                // 如果不存在库存记录，创建新记录
                logger.info("No inventory record found for product ID: {}, creating new record", productId);
                inventory = new StockInventory();
                inventory.setProductId(productId);
                inventory.setProductName(productName); // 设置商品名称
                inventory.setCurrentQuantity((long)quantity);
                inventory.setUpperLimit(9999L); // 设置默认库存上限
                inventory.setLowerLimit(0L);    // 设置默认库存下限
                inventory.setStatus("0");       // 0-正常状态
                
                // 使用默认的仓库和库位编码
                inventory.setWarehouseCode("WH001");
                inventory.setLocationCode("LOC001");
                
                stockInventoryService.insertStockInventory(inventory);
                logger.info("Created new inventory record for product: {}, quantity: {}", productName, quantity);
            } else {
                // 更新现有库存记录
                logger.info("Updating inventory for product: {}, current quantity: {}, adding: {}", 
                        productName, inventory.getCurrentQuantity(), quantity);
                
                // 如果名称为空或与新获取的名称不同，更新商品名称
                if (inventory.getProductName() == null || inventory.getProductName().isEmpty() || 
                    !inventory.getProductName().equals(productName)) {
                    inventory.setProductName(productName);
                    logger.info("Updating product name to: {}", productName);
                }
                
                // 增加库存数量
                long newQuantity = inventory.getCurrentQuantity() + quantity;
                inventory.setCurrentQuantity(newQuantity);
                
                stockInventoryService.updateStockInventory(inventory);
                logger.info("Updated inventory for product: {}, new quantity: {}", productName, newQuantity);
            }
        } catch (Exception e) {
            logger.error("Error updating inventory for purchase order: {}", event.getOrderId(), e);
        }
    }

    @Override
    public EventType getSupportedEventType() {
        return EventType.PURCHASE_ORDER_EXECUTED;
    }
    
    @Override
    public Class<OrderExecutionEvent> getSupportedEventClass() {
        return OrderExecutionEvent.class;
    }
} 